package com.wuyou.hard;

import java.util.*;

/**
 * 854. 相似度为 K 的字符串
 */
public class KSimilarity {

    public static void main(String[] args) {
        KSimilarity kSimilarity = new KSimilarity();
        String s1 = "abccaacceecdeea";
        String s2 = "bcaacceeccdeaae";

        System.out.println(kSimilarity.solution_1(s1, s2));
    }

    public int solution_1(String s1, String s2) {

        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();

        Map<Character, Map<Integer, Character>> map1 = new HashMap<>();
        Map<Character, Map<Integer, Character>> map2 = new HashMap<>();
        int res = 0;
        for (int i = 0; i < s1.length(); i++) {
            Map<Integer, Character> m1 = map1.getOrDefault(c1[i], new HashMap<Integer, Character>());
            m1.put(i, c1[i]);
            map1.put(c1[i], m1);
            Map<Integer, Character> m2 = map2.getOrDefault(c2[i], new HashMap<Integer, Character>());
            m2.put(i, c2[i]);
            map2.put(c2[i], m2);
        }

        Set<Character> k1 = map1.keySet();
        Set<Character> k2 = map2.keySet();
        for (int i = 0; i < k1.size(); i++) {
            Map<Integer, Character> map11 = map1.get(c1[i]);
            Map<Integer, Character> map22 = map2.get(c1[i]);
            Set<Integer> k11 = map11.keySet();
            Set<Integer> k22 = map22.keySet();

            Iterator i1 = k11.iterator();
            Iterator i2 = k22.iterator();
            while (i1.hasNext() && i2.hasNext()) {
                Integer next1 = (Integer) i1.next();
                Integer next2 = (Integer) i2.next();
                if (next1 != next2) {

                    char temp = c2[next1];
                    c2[next1] = c2[next2];
                    c2[next2] = temp;
                    res++;
                    map22.remove(next2);
                    map22.put(next1, c2[next1]);
                    map2.put(c2[next1], map22);
                    Map<Integer, Character> tempMap = map2.get(c2[next2]);

                    tempMap.remove(next1);
                    tempMap.put(next2, c2[next2]);
                    map2.put(c2[next2], tempMap);
                    i1 = k11.iterator();
                    i2 = k22.iterator();
//                    i--;
//                    break;
                }
            }

        }
        return res;
    }
}

